<template>
  <view class="wyf">
    <view class="img"><image :src="picUrl" mode="widthFix"></image></view>
    <view class="songs_details">
      <view class="songs_info">
        <text>{{ songsDetail[0].ar[0].name }}</text>
        <!-- <text v-if="t===1" class="pay" @click="payAttention(0)">已关注</text> -->
        <!-- <text v-else class="pay" @click="payAttention(1)">关注</text> -->
        <text class="pay">关注</text>
      </view>
      <image :class="['needle', isPlay ? 'needleroute' : '']" src="https://s1.ax1x.com/2022/08/27/vRgA5n.png" mode="widthFix"></image>
      <view :class="['songs_container', isPlay ? 'songs_container_animation' : '']">
        <image src="https://img.abeim.cn/imgs/2022/08/0a72129346aa0b4b.png" mode="widthFix"></image>
        <image :src="songsDetail[0].al.picUrl" mode="widthFix" class="pic"></image>
      </view>
      <view class="love_comment">
        <text v-if="islike === false" class="iconfont icon-xihuan-xianxing" @click="likeSongs(true)"></text>
        <text v-else-if="islike === true" class="iconfont icon-xihuan2" @click="likeSongs(false)"></text>
        <text class="iconfont icon-jianyi" @click="goComment"></text>
      </view>
      <view class="controlProcess">
        <text>{{ curentTime }}</text>
        <view class="cmPro">
          <cmdProgress activeColor="#fff" blockColor="#fff" blockOuterColor="pink" block-size="20" :value="curentProgress" @changing="changing" @changed="changed"></cmdProgress>
        </view>
        <text style=" transform: translateX(15rpx);">{{ allTime }}</text>
      </view>
      <view class="footer_container">
        <text class="iconfont icon-hanhan-01-01-copy"></text>
        <text class="iconfont icon-shangyishoushangyige-copy" @click="switchSongs('pre')"></text>
        <text :class="['iconfont', isPlay ? 'icon-bofang1-copy' : 'icon-bofang-copy']" style="font-size: 80rpx;" @click="handlePlayer"></text>
        <text class="iconfont icon-xiayigexiayishou-copy" @click="switchSongs('next')"></text>
        <text class="iconfont icon-list-copy"></text>
      </view>
    </view>
  </view>
</template>
<script>
const app = getApp({ allowDefault: true })
import { mapState } from 'vuex'
import cmdProgress from '@/subpkg/cmd-progress/cmd-progress.vue'
const dayjs = require('dayjs')
export default {
  name: 'songs_detail',
  data() {
    return {
      islike: false,
      love: '',
      // 是否关注1为关注其他为非关注
      // t: 1,
      isPlay: false,
      songsDetail: [],
      // personName: '',
      picUrl: '',
      level: 'lossless',
      auto: '',
      // 每个歌曲对应的id
      id: '',
      // 每个歌曲对应的数组索引
      index: '',
      // 为了避免重复发送请求所以发请求前看看页面中是否有对应的音乐链接如果有就不发没有再发
      musicLink: '',
      curentTime: '00:00',
      allTime: '00:00',
      curentProgress: '',
      // 控制是否应该更新进度条状态
      updateStatus: false
    }
  },
  components: {
    cmdProgress
  },
  computed: {
    ...mapState('login', ['cookie', 'userInfo', 'orUserinfo'])
  },
  onLoad(options) {
    this.id = options.id
    // console.log(this.id);
    this.getSongsDetail(options.id)

    if (this.userInfo.nickname) {
      setTimeout(() => {
        this.getLoveSongs(this.userInfo.userId)
        
      }, 1000)
    } else if (this.orUserinfo.nickname) {
      setTimeout(() => {
        this.getLoveSongs(this.orUserinfo.userId)
      }, 1000)
    }

    uni.$once('vals', data => {
      this.love = data
      // console.log(this.love);
    })
    if (app.globalData.musicIsPlayer === true && app.globalData.musicId === this.id) {
      this.isPlay = true
    }
    // 解决如果在手机端运行音乐软件外部的后台状态栏停止音乐播放和软件里面的不同步
    this.auto = uni.getBackgroundAudioManager()
    this.updateStatus = true
    setTimeout(() => {
      this.isPlay = true
      this.controlMusicPlay(this.id)
    }, 500)

    this.auto.onPlay(() => {
      app.globalData.musicId = this.id
      app.globalData.musicIsPlayer = true
      this.isPlay = true
    })
    this.auto.onPause(() => {
      this.isPlay = false
      app.globalData.musicIsPlayer = false
    })
    this.auto.onStop(() => {
      this.isPlay = false
      app.globalData.musicIsPlayer = false
    })
    this.auto.onTimeUpdate(() => {
      if (this.updateStatus) {
        this.curentTime = dayjs(this.auto.currentTime * 1000).format('mm:ss')
        // console.log(this.curentTime);
        this.curentProgress = (this.auto.currentTime / this.auto.duration) * 100
        // console.log(curentProgress);
      }
    })
    // 歌曲自然播放结束事件
    this.auto.onEnded(() => {
      this.switchSongs('next')
    })
    // 拿到推荐歌曲页面传过来的index的数组下标
    uni.$once('sendIndex', val => {
      // console.log(val);
      this.index = val
    })
  },
  onUnload() {
    if (this.love === '心动') {
      uni.navigateBack({
        delta: 2
      })
    }
  },
  methods: {
    async getLoveSongs(uid) {
      const { data: res } = await uni.$http.get('likelist', { uid,timestamp: new Date().getTime() })
      // console.log(res)
      if (res.code !== 200) return uni.$showMsg('喜欢歌曲列表获取失败')
      const rrr = res.ids.findIndex(item => {
        return item == this.id
      })
      // console.log(typeof  Number(this.id))
      // console.log(rrr)
      if (rrr !== -1) {
        this.islike = true
        // console.log(this.islike)
      } else {
        this.islike = false
        // console.log(this.islike)
      }
    },
    async likeSongs(like) {
      if (!this.cookie) {
        uni.$showMsg('登录后可同步自己的喜欢列表哦')
      } else {
        if (like === true) {
          const { data: res } = await uni.$http.get('like', { id: this.id, like })
          // console.log(res)
          if (res.code !== 200) return uni.$showMsg('添加至喜欢列表失败')
           this.islike = true
          this.getLoveSongs(this.userInfo.userId)
          return this.islike
         
        } else if (like === false) {
          const { data: res } = await uni.$http.get('like', { id: this.id, like })
          // console.log(res)
          if (res.code !== 200) return uni.$showMsg('取消喜欢失败')
            this.islike = false
          this.getLoveSongs(this.userInfo.userId)
          return this.islike
        
        }
      }
    },
    async getSongsDetail(id) {
      const { data: res } = await uni.$http.get('song/detail', { ids: id })
      // console.log(res)
      if (res.code !== 200) return uni.$showMsg('歌曲详情数据获取失败')
      this.songsDetail = res.songs

      let allTime = dayjs(this.songsDetail[0].dt).format('mm:ss')
      this.allTime = allTime
      this.picUrl = this.songsDetail[0].al.picUrl
      uni.setNavigationBarTitle({
        title: this.songsDetail[0].name
      })
    },
    handlePlayer() {
      this.isPlay = !this.isPlay
      this.controlMusicPlay(this.id, this.musicLink)
    },
    async controlMusicPlay(id, musicLink) {
      if (this.isPlay) {
        if (!musicLink) {
          const { data: res } = await uni.$http.get('song/url/v1', { id: id, level: this.level })
          // console.log(res)
          if (res.code !== 200) {
            this.isPlay = false
            return uni.$showMsg('播放失败')
          }
          this.musicLink = res.data[0].url
        }
        this.auto.src = musicLink ? musicLink : this.musicLink
        this.auto.title = this.songsDetail[0].name
      } else {
        this.auto.pause()
      }
    },
    async switchSongs(type) {
      this.auto.stop()
      if (type === 'next') {
        const { data: res } = await uni.$http.get('recommend/songs', { cookie: this.cookie })
        // console.log(res)
        if (res.code == 200) {
          if (this.index === res.data.dailySongs.length - 1) {
            this.index = -1
          }
          this.index += 1
          this.getSongsDetail(res.data.dailySongs[this.index].id)
          this.getLoveSongs(this.userInfo.userId)
          setTimeout(() => {
            this.isPlay = true
            this.controlMusicPlay(res.data.dailySongs[this.index].id)
            // console.log('111')
          }, 1500)
        }
      } else if (type === 'pre') {
        const { data: res } = await uni.$http.get('recommend/songs', { cookie: this.cookie })
        // console.log(res)
        if (res.code == 200) {
          if (this.index === 0) {
            this.index = res.data.dailySongs.length
          }
          this.index -= 1
          this.getSongsDetail(res.data.dailySongs[this.index].id)
          this.getLoveSongs(this.userInfo.userId)
          setTimeout(() => {
            this.isPlay = true
            this.controlMusicPlay(res.data.dailySongs[this.index].id)
          }, 1500)
        }
      }
    },
    changed(e) {
      if (this.auto.duration) {
        // console.log(e)
        // let jumpAfterTime=dayjs(e.value).format('mm:ss')
        // this.updateStatus=false
        this.auto.seek((e.value / 100) * this.auto.duration)
        this.curentProgress = e.value
        this.updateStatus = true
      }
    },
    changing(val) {
      // console.log(val);
      this.updateStatus = false
    },
    // 关注功能需要手机短信验证码所以就不实现了
    // async payAttention(t) {
    //   console.log(t)
    //   this.t=t
    //   const { data: res } = await uni.$http.get('follow', { id: this.songsDetail[0].ar[0].id, cookie: this.cookie, t: this.t })
    //   console.log(res)
    // }
    goComment() {
      uni.navigateTo({
        url: '/subpkg/comment/comment?id=' + this.id
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.wyf {
  height: 100vh;
  position: fixed;
  width: 100%;
}
.img image {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 10rpx;
  height: 100% !important;
  width: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  filter: blur(80rpx);
  transform: scale(1.2);
  // opacity: 0.3;
}
.songs_details {
  // background: linear-gradient(45deg, pink, skyblue, #ffb8ff);
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.songs_info {
  position: relative;
  top: -15rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 15rpx 0;
}
.songs_info text {
  font-size: 30rpx;
  color: #0c0b0b;
}
.songs_info .pay {
  // transform: translateY(-10rpx);
  font-size: 20rpx;
  border: 2rpx solid #a1b9be;
  border-radius: 10rpx;
  color: #ffffff;
  line-height: 30rpx;
  text-align: center;
  width: 50rpx;
  height: 30rpx;
  z-index: 120;
  transform: translateY(15rpx);
}
.songs_container {
  position: relative;
  bottom: 300rpx;
  // border: 2rpx solid red;
  margin: 0 auto;
}
.songs_container_animation {
  animation: wyf 20s linear 0.5s infinite forwards;
}
@keyframes wyf {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.songs_container image {
  width: 400rpx;
  height: 400rpx;
}
.needle {
  width: 300rpx;
  position: relative;
  left: 20%;
  transform: translate(-33.5rpx, -100rpx);
  z-index: 100;
  transform-origin: 236rpx -4rpx;
  transition: transform 0.5s 0.5s;
}
.needleroute {
  transform-origin: 236rpx -4rpx;
  transform: rotate(25deg);
  transition: transform 0.5s;
}
.songs_container .pic {
  position: absolute;
  width: 240rpx;
  height: 240rpx;
  border-radius: 50%;
  overflow: hidden;
  left: 0;
  top: 0;
  right: 0;
  bottom: 10rpx;
  margin: auto;
}
.footer_container {
  z-index: 100;
}
.iconfont {
  width: 80rpx;
  height: 80rpx;
  font-size: 60rpx;
  margin: 0 40rpx;
  vertical-align: middle;
}
.controlProcess {
  position: relative;
  display: flex;
  bottom: 60rpx;
  width: 600rpx;
  height: 80rpx;
  justify-content: center;
  align-items: center;
}
.cmPro {
  // transform: translateX(25rpx);
}
.controlProcess text {
  font-size: 16rpx;
  transform: translateX(-15rpx);
}
.love_comment {
  position: relative;
  display: flex;
  z-index: 100;
  // justify-content: center;
  // align-items: center;
  bottom: 60rpx;
}
</style>
